package com.yy.micro.magic.ext.domain.code;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Deprecated
public class CodeProviders {

    private List<CodeMapProvider> providers;
    private Map<String,CodeMapProvider> providerMap = new HashMap<>(8);

    public List<CodeMapProvider> getProviders() {
        return providers;
    }

    @Autowired(required = false)
    public void setProviders(final List<CodeMapProvider> providers) {
        if (null == this.providers){
            this.providers = new ArrayList<>();
        }
        if (!CollectionUtils.isEmpty(providers)){
            this.providers.addAll(providers);
            providers.forEach(p->{
                addMapProvider(p);
            });
        }
    }

    public void addProvider(CodeMapProvider provider){
        if (null== this.providers){
            this.providers = new ArrayList<>();
        }
        if (null != provider){
            this.providers.add(provider);
            addMapProvider(provider);
        }
    }

    private void addMapProvider(CodeMapProvider provider){
        CodeMapProvider mapProvider = providerMap.get(provider.getPlanCode());
        if (null == mapProvider){
            providerMap.put(provider.getPlanCode(),provider);
        }else{
            mapProvider.setCodeMaps(provider.getCodeMaps());
        }
    }

    /**
     * map code table and find target value by value
     * @param planCode
     * @param name
     * @param value
     * @return
     */
    public Object findCodeTargetValue(String planCode,String name,Object value){
        return findCodeTargetValue(planCode,name,value,value);
    }

    /**
     * map code table and find target value by value,return default value if not find codetable.
     * @param planCode  plan code
     * @param name  code table name
     * @param value  value
     * @param defaultValue  return default value if not find code table.
     * @return
     */
    public Object findCodeTargetValue(String planCode,String name,Object value,Object defaultValue){
        if (providerMap.containsKey(planCode)){
            CodeMapProvider provider = providerMap.get(planCode);
            return provider.findCodeTargetValue(name,value,defaultValue);
        }
        return defaultValue;
    }

    /**
     * map code table and find code item by value,return null if not find.
     * @param planCode  plan code
     * @param name  code table name
     * @param value code value
     * @return
     */
    public CodeMapItem findCodeMapItem(String planCode,String name,Object value){
        if (providerMap.containsKey(planCode)){
            CodeMapProvider provider = providerMap.get(planCode);
            return provider.findCodeMapItem(name,value);
        }
        return null;
    }
}
